﻿using System;
using System.Data;
using System.Web.UI.WebControls;
using System.Collections.Generic;
using Infragistics.WebUI.UltraWebGrid;
using System.IO;
using uMES.LeanManufacturing.ReportBusiness;
using uMES.LeanManufacturing.ParameterDTO;
using iTextSharp.text;
using iTextSharp.text.pdf;
using QRCoder;
using System.Drawing;
using System.Web.UI;
using System.Configuration;
using System.Web;

public partial class RejectApp2Form : ShopfloorPage, INormalReport
{
    const string QueryWhere = "RejectApp2Form";
    uMESCommonBusiness common = new uMESCommonBusiness();
    uMESRejectAppBusiness rejectapp = new uMESRejectAppBusiness();
    uMESAssemblyRecordBusiness assembly = new uMESAssemblyRecordBusiness();

    string businessName = "质量管理", parentName = "rejectappinfo";
    protected void Page_Load(object sender, EventArgs e)
    {
        uMESMasterPage master = this.Master as uMESMasterPage;
        master.strNavigation = "当前位置：三级审理";
        master.strTitle = "三级审理";
        master.ChangeFrame(true);
        NormalReportControl normalCntrl = new NormalReportControl();
        normalCntrl.LtnFirst = lbtnFirst;
        normalCntrl.LtnLast = lbtnLast;
        normalCntrl.LtnNext = lbtnNext;
        normalCntrl.LtnPrev = lbtnPrev;
        normalCntrl.BtnReset = btnReSet;
        normalCntrl.BtnGo = btnGo;
        normalCntrl.BtnSearch = btnSearch;
        normalCntrl.LabPages = lLabel1;
        normalCntrl.TxtPage = txtPage;
        normalCntrl.TxtTotalPage = txtTotalPage;
        normalCntrl.TxtCurrentPage = txtCurrentPage;
        normalCntrl.NormalOperation = this;
        normalCntrl.QueryWhere = QueryWhere;

        WebPanel = WebAsyncRefreshPanel1;

        if (!IsPostBack)
        {
            ClearMessage_PageLoad();
            GetLossReason();
            BindRejectAppLevel();
            BindResponsibleDepartment();

        }
    }

    #region 获取报废原因
    protected void GetLossReason()
    {
        DataTable DT = common.GetLossReason();

        ddlLossReason.DataTextField = "LossReasonName";
        ddlLossReason.DataValueField = "LossReasonID";
        ddlLossReason.DataSource = DT;
        ddlLossReason.DataBind();
    }
    #endregion


    #region 绑定审理级别
    protected void BindRejectAppLevel()
    {


        System.Web.UI.WebControls.ListItem item = new System.Web.UI.WebControls.ListItem();

        item = new System.Web.UI.WebControls.ListItem("一级审理", "1");
        ddlAssessmentLevel.Items.Add(item);

        item = new System.Web.UI.WebControls.ListItem("二级审理", "2");
        ddlAssessmentLevel.Items.Add(item);

        item = new System.Web.UI.WebControls.ListItem("三级审理", "3");
        ddlAssessmentLevel.Items.Add(item);

        ddlAssessmentLevel.SelectedIndex = ddlAssessmentLevel.Items.Count - 1;ddlAssessmentLevel.Enabled = false;

    }
    #endregion

    #region 绑定责任部门
    protected void BindResponsibleDepartment()
    {
        DataTable dt = common.GetFactoryNames();
        ddlResponsibleDepartment.DataTextField = "factoryname";
        ddlResponsibleDepartment.DataValueField = "factoryid";
        ddlResponsibleDepartment.DataSource = dt;
        ddlResponsibleDepartment.DataBind();

        ddlResponsibleDepartment.Items.Insert(0, "");
    }
    #endregion

    #region 重置
    protected void btnReSet_Click(object sender, EventArgs e)
    {
        txtProcessNo.Text = string.Empty;
        txtContainerName.Text = string.Empty;
        txtProductName.Text = string.Empty;
        txtSpecName.Text = string.Empty;
        txtStartDate.Value = string.Empty;
        txtEndDate.Value = string.Empty;

        ClearContainerDisp();
        ClearRejectAppDisp();
    }

    protected void ClearContainerDisp()
    {
        txtDispProcessNo.Text = string.Empty;
        txtDispOprNo.Text = string.Empty;
        txtDispContainerName.Text = string.Empty;
        txtDispContainerID.Text = string.Empty;
        txtDispWorkflowID.Text = string.Empty;
        txtDispProductName.Text = string.Empty;
        txtDispProductID.Text = string.Empty;
        txtDispDescription.Text = string.Empty;
        txtDispContainerQty.Text = string.Empty;
        txtChildCount.Text = string.Empty;
        txtDispPlannedStartDate.Text = string.Empty;
        txtDispPlannedCompletionDate.Text = string.Empty;
    }

    protected void ClearRejectAppDisp()
    {
        txtID.Text = string.Empty;
        txtStatus.Text = string.Empty;
        txtDispRejectAppInfoName.Text = string.Empty;
        txtDispSpecName.Text = string.Empty;
        txtDispQty.Text = string.Empty;
        txtDispSubmitFullName.Text = string.Empty;
        txtDispSubmitDate.Text = string.Empty;
        txtDispQualityNotes.InnerHtml = string.Empty;
        txtDisposeNotes.Text = string.Empty;
        txtDisposeNotes2.Text = string.Empty;
        txtDisposeNotes3.Text = string.Empty;

        txtRBQty.Text = string.Empty;
        txtFxQty.Text = string.Empty;
        txtBFQty.Text = string.Empty;

        if (ddlLossReason.Items.Count > 0)
        { ddlLossReason.SelectedIndex = 0; }

        //if (ddlAssessmentLevel.Items.Count > 0)
        //{ ddlAssessmentLevel.SelectedIndex = ddlAssessmentLevel.Items.Count - 1; }

        if (ddlResponsibleDepartment.Items.Count > 0)
        { ddlResponsibleDepartment.SelectedIndex = 0; }
    }
    #endregion

    #region 数据查询
    public Dictionary<string, string> GetQuery()
    {
        string strProcessNo = txtProcessNo.Text.Trim();
        string strContainerName = txtContainerName.Text.Trim();
        string strProductName = txtProductName.Text.Trim();
        string strSpecName = txtSpecName.Text.Trim();
        string strStartDate = txtStartDate.Value.Trim();
        string strEndDate = txtEndDate.Value.Trim();

        Dictionary<string, string> result = new Dictionary<string, string>();
        result.Add("ProcessNo", strProcessNo);
        result.Add("ContainerName", strContainerName);
        result.Add("ProductName", strProductName);
        result.Add("SpecName", strSpecName);
        result.Add("StartDate", strStartDate);
        result.Add("EndDate", strEndDate);
        result.Add("Status", "35");//质量师审核之后

        Session[QueryWhere] = result;

        return result;
    }

    public void QueryData(Dictionary<string, string> query)
    {
        ClearMessage();

        try
        {
            uMESPagingDataDTO result = rejectapp.GetSourceData(query, Convert.ToInt32(this.txtCurrentPage.Text), 15);
            this.ItemGrid.DataSource = result.DBTable;
            this.ItemGrid.DataBind();
            this.txtTotalPage.Text = result.PageCount;
            if (result.RowCount == "0")
            {
                this.txtCurrentPage.Text = "0";
            }
            lLabel1.Text = string.Format("第 {0} 页  共 {1} 页", this.txtCurrentPage.Text, this.txtTotalPage.Text);
            this.txtPage.Text = this.txtCurrentPage.Text;

            ClearContainerDisp();
            ClearRejectAppDisp();
        }
        catch (Exception ex)
        {
            DisplayMessage(ex.Message, false);
        }
    }

    public void ResetQuery()
    {
        Session[QueryWhere] = "";
        txtScan.Text = string.Empty;
        txtProcessNo.Text = string.Empty;
        txtContainerName.Text = string.Empty;
        txtProductName.Text = string.Empty;
        txtSpecName.Text = string.Empty;
        txtStartDate.Value = string.Empty;
        txtEndDate.Value = string.Empty;
        txtProductNo.Text = string.Empty;
        ItemGrid.Rows.Clear();

        this.txtTotalPage.Text = "";
        this.txtCurrentPage.Text = "";
        this.txtPage.Text = "";
        lLabel1.Text = "第  页  共  页";
    }
    #endregion

    #region 分页按钮
    protected void lbtnFirst_Click(object sender, EventArgs e)
    {

    }
    protected void lbtnPrev_Click(object sender, EventArgs e)
    {

    }
    protected void lbtnNext_Click(object sender, EventArgs e)
    {

    }
    protected void lbtnLast_Click(object sender, EventArgs e)
    {

    }
    protected void btnGo_Click(object sender, EventArgs e)
    {

    }
    #endregion

    protected void txtScan_TextChanged(object sender, EventArgs e)
    {
        ClearMessage();

        try
        {
            string strScan = txtScan.Text.Trim();
            txtScan.Text = "";

            if (strScan != string.Empty)
            {
                Dictionary<string, string> para = new Dictionary<string, string>();
                para.Add("ScanContainerName", strScan);
                para.Add("Status", "35");

                Session[QueryWhere] = para;

                txtCurrentPage.Text = "1";
                QueryData(para);
            }
        }
        catch (Exception ex)
        {
            DisplayMessage(ex.Message, false);
        }
    }

    protected void ItemGrid_ActiveRowChange(object sender, RowEventArgs e)
    {
        ClearMessage();
        ClearContainerDisp();
        try
        {
            string strContainerName = e.Row.Cells.FromKey("ContainerName").Value.ToString();
            DataTable DT = assembly.GetContainerInfo(strContainerName);

            if (DT.Rows.Count > 0)
            {
                string strProcessNo = DT.Rows[0]["ProcessNo"].ToString();
                txtDispProcessNo.Text = strProcessNo;

                string strOprNo = DT.Rows[0]["OprNo"].ToString();
                txtDispOprNo.Text = strOprNo;

                txtDispContainerName.Text = strContainerName;

                string strContainerID = DT.Rows[0]["ContainerID"].ToString();
                txtDispContainerID.Text = strContainerID;

                string strWorkflowID = DT.Rows[0]["WorkflowID"].ToString();
                txtDispWorkflowID.Text = strWorkflowID;

                string strProductName = DT.Rows[0]["ProductName"].ToString();
                txtDispProductName.Text = strProductName;
                string strProductID = DT.Rows[0]["ProductID"].ToString();
                txtDispProductID.Text = strProductID;

                string strDescription = DT.Rows[0]["Description"].ToString();
                txtDispDescription.Text = strDescription;

                string strContainerQty = DT.Rows[0]["Qty"].ToString();
                txtDispContainerQty.Text = strContainerQty;

                string strPlannedStartDate = DT.Rows[0]["PlannedStartDate"].ToString();
                if (strPlannedStartDate != string.Empty)
                {
                    txtDispPlannedStartDate.Text = Convert.ToDateTime(strPlannedStartDate).ToString("yyyy-MM-dd");
                }

                string strPlannedCompletionDate = DT.Rows[0]["PlannedCompletionDate"].ToString();
                if (strPlannedCompletionDate != string.Empty)
                {
                    txtDispPlannedCompletionDate.Text = Convert.ToDateTime(strPlannedCompletionDate).ToString("yyyy-MM-dd");
                }
            }

            txtID.Text = string.Empty;
            string strID = e.Row.Cells.FromKey("ID").Value.ToString();
            txtID.Text = strID;

            txtStatus.Text = string.Empty;
            string strStatus = e.Row.Cells.FromKey("Status").Value.ToString();
            txtStatus.Text = strStatus;

            txtDispRejectAppInfoName.Text = string.Empty;
            string strRejectAppInfoName = e.Row.Cells.FromKey("RejectAppInfoName").Value.ToString();
            txtDispRejectAppInfoName.Text = strRejectAppInfoName;

            txtDispSpecName.Text = string.Empty;
            string strSpecName = e.Row.Cells.FromKey("SpecNameDisp").Value.ToString();
            txtDispSpecName.Text = strSpecName;

            txtDispQty.Text = string.Empty;
            string strQty = e.Row.Cells.FromKey("Qty").Value.ToString();
            txtDispQty.Text = strQty;

            txtDispSubmitFullName.Text = string.Empty;
            string strSubmitFullName = e.Row.Cells.FromKey("SubmitFullName").Value.ToString();
            txtDispSubmitFullName.Text = strSubmitFullName;

            //显示不合格信息描述
            txtDispQualityNotes.InnerHtml = string.Empty;
            if (e.Row.Cells.FromKey("QualityNotes").Value != null)
            {
                string strQualityNotes = "";
                ParseCode(e.Row.Cells.FromKey("QualityNotes").Text, ref strQualityNotes);
                txtDispQualityNotes.InnerHtml = strQualityNotes;
            }

            txtDispSubmitDate.Text = string.Empty;
            if (e.Row.Cells.FromKey("SubmitDate").Value != null)
            {
                string strSubmitDate = e.Row.Cells.FromKey("SubmitDate").Value.ToString();
                txtDispSubmitDate.Text = Convert.ToDateTime(strSubmitDate).ToString("yyyy-MM-dd");
            }

            txtDisposeNotes.Text = string.Empty;
            if (e.Row.Cells.FromKey("DisposeNotes").Value != null)
            {
                string strDisposeNotes = "";
                if (!string.IsNullOrWhiteSpace(e.Row.Cells.FromKey("DesignEmpNotes").Text))
                {
                    strDisposeNotes = "设计：" + e.Row.Cells.FromKey("DesignEmpNotes").Text + "\r\n\r\n";
                }
                strDisposeNotes += "工艺：" + e.Row.Cells.FromKey("DisposeNotes").Text;
                txtDisposeNotes.Text = strDisposeNotes;
            }

            //产品序号
            //DataTable dtProductNo = rejectapp.GetProductNoByRejectApp(strID);
            //责任部门展示
            ddlResponsibleDepartment.SelectedValue = e.Row.Cells.FromKey("ResponsibleDepartment").Text;
            //质量信息展示
            txtDisposeNotes2.Text = e.Row.Cells.FromKey("DisposeNotes2").Text;

        }
        catch (Exception ex)
        {
            DisplayMessage(ex.Message, false);
        }
    }

    #region 保存按钮
    protected void btnSave_Click(object sender, EventArgs e)
    {
        ClearMessage();

        try
        {
            string strID = txtID.Text;
            if (strID == string.Empty)
            {
                DisplayMessage("请选择要审核的不合格品审理单", false);
                return;
            }

            if (ddlAssessmentLevel.SelectedValue != "3") {
                DisplayMessage("只能选择3级审理", false);
                return;
            }

            int intRBQty = 0;
            int intFixQty = 0;
            int intScrapQty = 0;
            DataTable dtProductNo = new DataTable();
            if (CheckData(out dtProductNo, out intRBQty, out intFixQty, out intScrapQty) == false)
            {
                return;
            }

            Dictionary<string, string> userInfo = Session["UserInfo"] as Dictionary<string, string>;
            string strOprEmployeeID = userInfo["EmployeeID"];

            Dictionary<string, string> paraH = new Dictionary<string, string>();
            paraH.Add("RejectAppInfoID", strID);
            paraH.Add("OprType", "40");
            paraH.Add("OprEmployeeID", strOprEmployeeID);
            paraH.Add("OprDate", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            paraH.Add("Notes", "");
            paraH.Add("AssessmentLevel", ddlAssessmentLevel.SelectedValue);

            string strDisposeNotes2 = txtDisposeNotes2.Text.Trim();
            string strDisposeNotes3 = txtDisposeNotes3.Text.Trim();

            Dictionary<string, string> paraM = new Dictionary<string, string>();
            paraM.Add("Status", "40");
            paraM.Add("DisposeNotes2", strDisposeNotes2);
            paraM.Add("DisposeNotes3", strDisposeNotes3);
            paraM.Add("RBQty", intRBQty.ToString());
            paraM.Add("FixQty", intFixQty.ToString());
            paraM.Add("ScrapQty", intScrapQty.ToString());
            paraM.Add("ResponsibleDepartment", ddlResponsibleDepartment.SelectedValue);

            rejectapp.AppRejectAppInfo(paraH, paraM, dtProductNo);

            #region 记录日志
            var ml = new MESAuditLog();
            ml.ContainerName = txtDispContainerName.Text; ml.ContainerID = txtDispContainerID.Text;
            ml.ParentID = strID; ml.ParentName = parentName;
            ml.CreateEmployeeID = userInfo["EmployeeID"];
            ml.BusinessName = businessName; ml.OperationType = 1;
            ml.Description = string.Format("不合格审理:" + txtDispSpecName.Text + ",三级审理保存到校验,让步:'{0}',返修:'{1}',报废:'{2}'",
                intRBQty, intFixQty, intScrapQty);
            common.SaveMESAuditLog(ml);
            #endregion

            QueryData(GetQuery());

            ClearContainerDisp();
            ClearRejectAppDisp();

            DisplayMessage("保存成功", true);
        }
        catch (Exception ex)
        {
            DisplayMessage(ex.Message, false);
        }
    }

    #region 数据验证
    protected Boolean CheckData(out DataTable dtProductNo, out int intRBQty, out int intFixQty, out int intScrapQty)
    {
        DataTable DT = new DataTable();
        DT.Columns.Add("ID");
        DT.Columns.Add("Qty");
        DT.Columns.Add("DisposeResult");
        DT.Columns.Add("LossReasonID");

        intRBQty = 0;
        intFixQty = 0;
        intScrapQty = 0;

        string strDisposeNotes2 = txtDisposeNotes2.Text.Trim();
        if (strDisposeNotes2 == string.Empty)
        {
            //DisplayMessage("请填写部门意见", false);
            //txtDisposeNotes2.Focus();
            //dtProductNo = null;
            //return false;
        }

        string strDisposeNotes3 = txtDisposeNotes3.Text.Trim();
        if (strDisposeNotes3 == string.Empty)
        {
            DisplayMessage("请填写审理意见", false);
            txtDisposeNotes3.Focus();
            dtProductNo = null;
            return false;
        }

        if (txtRBQty.Text == "" && txtFxQty.Text == "" && txtBFQty.Text == "")
        {
            DisplayMessage("审理结论不能为空", false);
            txtRBQty.Focus();
            dtProductNo = null;
            return false;
        }

        if (ddlResponsibleDepartment.SelectedValue == string.Empty)
        {
            DisplayMessage("责任部门不能为空", false);
            ddlResponsibleDepartment.Focus();
            dtProductNo = null;
            return false;
        }

        DataTable dtProductNo1 = rejectapp.GetProductNoByRejectApp(txtID.Text);

        if (txtRBQty.Text != "")
        {
            if (txtRBQty.Text.Contains("."))
            {
                DisplayMessage("让步使用数量应为正数", false);
                txtRBQty.Focus();
                dtProductNo = null;
                return false;
            }
            else
            {
                try
                {


                    if (Convert.ToInt32(txtRBQty.Text) <= 0)
                    {
                        DisplayMessage("让步使用数量应为正整数", false);
                        txtRBQty.Focus();
                        dtProductNo = null;
                        return false;
                    }
                }
                catch
                {
                    DisplayMessage("让步使用数量应为数字", false);
                    txtRBQty.Focus();
                    dtProductNo = null;
                    return false;
                }
            }

            DataRow row = DT.NewRow();

            if (dtProductNo1.Rows.Count > 0)
            {
                row["ID"] = dtProductNo1.Rows[0]["ID"].ToString();
                dtProductNo1.Rows[0].Delete();
                dtProductNo1.AcceptChanges();
            }
            else
            {
                row["ID"] = string.Empty;
            }

            row["Qty"] = txtRBQty.Text;
            row["DisposeResult"] = 10;
            row["LossReasonID"] = "";
            DT.Rows.Add(row);
            intRBQty = Convert.ToInt32(txtRBQty.Text);
        }


        if (txtFxQty.Text != "")
        {
            if (txtFxQty.Text.Contains("."))
            {
                DisplayMessage("返工/返修数量应为正数", false);
                txtFxQty.Focus();
                dtProductNo = null;
                return false;
            }
            else
            {
                try
                {


                    if (Convert.ToInt32(txtFxQty.Text) <= 0)
                    {
                        DisplayMessage("返工/返修数量应为正整数", false);
                        txtFxQty.Focus();
                        dtProductNo = null;
                        return false;
                    }
                }
                catch
                {
                    DisplayMessage("返工/返修数量应为数字", false);
                    txtFxQty.Focus();
                    dtProductNo = null;
                    return false;
                }
            }
            DataRow row = DT.NewRow();

            if (dtProductNo1.Rows.Count > 0)
            {
                row["ID"] = dtProductNo1.Rows[0]["ID"].ToString();
                dtProductNo1.Rows[0].Delete();
                dtProductNo1.AcceptChanges();
            }
            else
            {
                row["ID"] = string.Empty;
            }
            row["Qty"] = txtFxQty.Text;
            row["DisposeResult"] = 20;
            row["LossReasonID"] = "";
            DT.Rows.Add(row);
            intFixQty = Convert.ToInt32(txtFxQty.Text);
        }

        if (txtBFQty.Text != "")
        {
            if (txtBFQty.Text.Contains("."))
            {
                DisplayMessage("报废数量应为正数", false);
                txtBFQty.Focus();
                dtProductNo = null;
                return false;
            }
            else
            {
                try
                {


                    if (Convert.ToInt32(txtBFQty.Text) <= 0)
                    {
                        DisplayMessage("报废数量应为正整数", false);
                        txtBFQty.Focus();
                        dtProductNo = null;
                        return false;
                    }
                }
                catch
                {
                    DisplayMessage("报废数量应为数字", false);
                    txtBFQty.Focus();
                    dtProductNo = null;
                    return false;
                }
            }
            DataRow row = DT.NewRow();

            if (dtProductNo1.Rows.Count > 0)
            {
                row["ID"] = dtProductNo1.Rows[0]["ID"].ToString();
                dtProductNo1.Rows[0].Delete();
                dtProductNo1.AcceptChanges();
            }
            else
            {
                row["ID"] = string.Empty;
            }

            row["Qty"] = txtBFQty.Text;
            row["DisposeResult"] = 30;
            row["LossReasonID"] = ddlLossReason.SelectedValue;
            DT.Rows.Add(row);

            intScrapQty = Convert.ToInt32(txtBFQty.Text);
        }
        if (txtRBQty.Text != "" && ddlAssessmentLevel.SelectedValue=="3")
        {
            //DisplayMessage("让步使用时，审理级别必须为二级及以上", false);
            //ddlAssessmentLevel.Focus();
            //dtProductNo = null;
            //return false;
        }

        if (txtBFQty.Text != "" && ddlLossReason.SelectedValue == null)
        {
            DisplayMessage("请选择报废原因", false);
            ddlLossReason.Focus();
            dtProductNo = null;
            return false;
        }


        int intQty = Convert.ToInt32(txtDispQty.Text);
        if ((intRBQty + intFixQty + intScrapQty) != intQty)
        {
            DisplayMessage("总数量应等于不合格品数量", false);
            dtProductNo = null;
            return false;
        }

        dtProductNo = DT;
        return true;
    }
    #endregion
    #endregion

    protected void ItemGrid_DataBound(object sender, EventArgs e)
    {
        for (int i = 0; i < ItemGrid.Rows.Count; i++)
        {
            if (ItemGrid.Rows[i].Cells.FromKey("SpecName").Value != null)
            {
                string strSpecName = ItemGrid.Rows[i].Cells.FromKey("SpecName").Value.ToString();
                ItemGrid.Rows[i].Cells.FromKey("SpecNameDisp").Value = common.GetSpecNameWithOutProdName(strSpecName);
            }
        }
    }




    protected void Button1_Click(object sender, EventArgs e)
    {
        try
        {
            ClearMessage();

            UltraGridRow uldr = ItemGrid.DisplayLayout.ActiveRow;
            if (uldr == null)
            {
                DisplayMessage("请选择订单记录", false);
                //Infragistics.WebUI.Shared.CallBackManager.AddScriptBlock(Page, WebAsyncRefreshPanel1, "<script>alert('请选择批次记录')</script>");
                return;
            }

            DataTable poupDt = new DataTable();
            poupDt.Columns.Add("ProductID");
            poupDt.Columns.Add("WorkflowID");
            DataRow newRow = poupDt.NewRow();
            newRow["ProductID"] = uldr.Cells.FromKey("ProductID").Text;
            newRow["WorkflowID"] = uldr.Cells.FromKey("Workflowid").Text;
            poupDt.Columns.Add("ContainerID"); poupDt.Columns.Add("ContainerName");
            newRow["ContainerID"] = uldr.Cells.FromKey("ContainerID").Text;
            newRow["ContainerName"] = uldr.Cells.FromKey("ContainerName").Text;
            poupDt.Rows.Add(newRow);
            Session.Add("ProcessDocument", poupDt);
            string strScript = string.Empty;

            //strScript = "<script>window.showModalDialog('Custom/bwCommonPage/uMESDocumentViewPopupForm.aspx', '', 'dialogWidth: 700px; dialogHeight: 600px; status = no; center: Yes; resizable: NO; ')</script>";
            //Infragistics.WebUI.Shared.CallBackManager.AddScriptBlock(Page, WebAsyncRefreshPanel1, strScript);
            var page = "Custom/bwCommonPage/uMESDocumentViewPopupForm.aspx";
            var script = String.Format("<script>OpenPopupWindow(false,'{0}','dialogWidth={1}px;dialogHeight={2}px;status=0');</script>", page, 700, 600);
            Infragistics.WebUI.Shared.CallBackManager.AddScriptBlock(Page, WebAsyncRefreshPanel1, script);
        }
        catch (Exception ex)
        {
            DisplayMessage(ex.Message, false);
        }
    }

    protected void Button2_Click(object sender, EventArgs e)
    {
        try
        {

            ClearMessage();

            UltraGridRow uldr = ItemGrid.DisplayLayout.ActiveRow;
            if (uldr == null)
            {
                DisplayMessage("请选择订单记录", false);
                //Infragistics.WebUI.Shared.CallBackManager.AddScriptBlock(Page, WebAsyncRefreshPanel1, "<script>alert('请选择批次记录')</script>");
                return;
            }

            string strContainerID = uldr.Cells.FromKey("containerid").Text;
            string strSpecID = uldr.Cells.FromKey("specid").Text;
            string strWorkflowID = uldr.Cells.FromKey("WorkflowID").Text;
            string strScript = string.Empty;
            strScript = "<script>window.showModalDialog('Custom/bwDataCollect/uMESDataCollectDetailInfoPopupForm.aspx?ContainerID=" + strContainerID + "&SpecID=" + strSpecID + "&WorkflowID=" + strWorkflowID + "', '', 'dialogWidth: 1080px; dialogHeight: 600px; status = no; center: Yes; resizable: NO; ')</script>";
            Infragistics.WebUI.Shared.CallBackManager.AddScriptBlock(Page, WebAsyncRefreshPanel1, strScript);
        }
        catch (Exception ex)
        {
            DisplayMessage(ex.Message, false);
        }
    }

    protected void Button3_Click(object sender, EventArgs e)
    {
        try {
            var re= ElevateLevel ();
            if (re.IsSuccess)
            {
                #region 记录日志
                Dictionary<string, string> userInfo = Session["UserInfo"] as Dictionary<string, string>;
                var ml = new MESAuditLog();
                ml.ContainerName = txtDispContainerName.Text; ml.ContainerID = txtDispContainerID.Text;
                ml.ParentID = re.Data.ToString(); ml.ParentName = parentName;
                ml.CreateEmployeeID = userInfo["EmployeeID"];
                ml.BusinessName = businessName; ml.OperationType = 1;
                ml.Description = "不合格审理:" + txtDispSpecName.Text + ",三级审理提升到二级";
                common.SaveMESAuditLog(ml);
                #endregion

                QueryData(GetQuery());

                ClearContainerDisp();
                ClearRejectAppDisp();

                DisplayMessage("保存成功", true);
            }
            else {
                DisplayMessage(re.Message, false);
            }
        } catch (Exception ex) {
            DisplayMessage(ex.Message, false);
        }
    }

    /// <summary>
    /// 提升级别
    /// </summary>
    /// <returns></returns>
    ResultModel ElevateLevel() {
        ResultModel re = new ResultModel();

        string strID = txtID.Text;
        if (strID == string.Empty)
        {
            return new ResultModel(false, "请选择要审核的不合格品审理单");
        }

        if (string.IsNullOrWhiteSpace(txtDisposeNotes3.Text)) {
          //  return new ResultModel(false, "请录入意见");
        }
        //if (ddlAssessmentLevel.SelectedValue != "2") {
        //    return new ResultModel(false, "只能提升到2级");
        //}

        Dictionary<string, string> userInfo = Session["UserInfo"] as Dictionary<string, string>;
        string strOprEmployeeID = userInfo["EmployeeID"];

        Dictionary<string, string> paraH = new Dictionary<string, string>();
        string strDisposeNotes3 = txtDisposeNotes3.Text.Trim();
        paraH.Add("RejectAppInfoID", strID);
        paraH.Add("OprType", "38");//提升级别到2级
        paraH.Add("OprEmployeeID", strOprEmployeeID);
        paraH.Add("OprDate", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
        paraH.Add("Notes", strDisposeNotes3);
        paraH.Add("AssessmentLevel", "2");//ddlAssessmentLevel.SelectedValue


        Dictionary<string, string> paraM = new Dictionary<string, string>();
        paraM.Add("Status", "38");

        rejectapp.AppRejectAppInfo(paraH, paraM, new DataTable());

        re.Data = strID;//返回ID，日志用
        re.IsSuccess = true;
        return re;
    }

    #region 特殊字符转换

    public void ParseCode(String strPreviewCode, ref string strPreviewCodeDis)
    {
        try
        {
            string webRootDir = HttpRuntime.AppDomainAppPath;
            string webRootUrl = "~";

            String strPreviewCodeTemp, strHtmlStripped, strTemp, strCodeTemp;
            String strFileDoc, strFileTemp, strFilePath, strFileName, strMapPath, strHtml;
            int intStartFlag, intEndFlag, intFlag1, intFlag2, intCodeStartFlag, intCodeEndFlag;
            String strImageIndex;
            clsParseCode oParse = new clsParseCode();
            Bitmap objBmp;
            String strLeft, strUp, strDown, strRight;

            strPreviewCode = strPreviewCode.Trim().Replace("\r\n\t\t", "");
            strPreviewCode = strPreviewCode.Trim().Replace("<P>", "");
            strPreviewCode = strPreviewCode.Trim().Replace("</P>", "");
            strPreviewCode = strPreviewCode.Replace("\"", "'");

            intStartFlag = strPreviewCode.IndexOf("<Image>");
            intEndFlag = strPreviewCode.IndexOf("</Image>");
            strHtmlStripped = "";
            strHtml = "";

            //strMapPath = MapPath("~");
            //strFileTemp = strMapPath + @"\Images\";

            //clsCon oCon = new clsCon();
            String strImagePath;
            //strImagePath = oCon.LoadConfigString("ImageGetPath");

            strImagePath = webRootDir + ConfigurationManager.AppSettings["ImageGetPath"].ToString();

            strFileTemp = strImagePath;

            uMESExternalControl.ToleranceInputLib.clsDrawImage oDraw = new uMESExternalControl.ToleranceInputLib.clsDrawImage();
            DataTable dtImage = new DataTable();

            while (intStartFlag > -1)
            {
                if (intStartFlag > 0)
                {
                    //将纯文本输出
                    strHtml = strPreviewCode.Substring(0, intStartFlag);
                    strPreviewCode = strPreviewCode.Substring(intStartFlag);
                    strPreviewCodeDis += strHtml;
                    intStartFlag = strPreviewCode.IndexOf("<Image>");
                    intEndFlag = strPreviewCode.IndexOf("</Image>");
                    continue;
                }

                else
                {
                    strHtml = "";
                    strPreviewCodeTemp = strPreviewCode.Substring(intStartFlag + 7, intEndFlag - intStartFlag - 7);
                    intCodeStartFlag = strPreviewCodeTemp.IndexOf("<&70><+>");
                    intCodeEndFlag = strPreviewCodeTemp.IndexOf("<+><&90>");

                    if (intCodeStartFlag > -1)
                    {
                        //代码为行位公差时
                        strCodeTemp = strPreviewCodeTemp.Replace("<&70><+>", "");
                        strCodeTemp = strCodeTemp.Replace("<+><&90>", "");

                        intFlag1 = strCodeTemp.IndexOf("<");
                        intFlag2 = strCodeTemp.IndexOf(">");
                        while (intFlag1 > -1)
                        {
                            strTemp = strCodeTemp.Substring(intFlag1, intFlag2 - intFlag1 + 1);
                            strCodeTemp = strCodeTemp.Replace(strTemp, "");
                            intFlag1 = strCodeTemp.IndexOf("<");
                            intFlag2 = strCodeTemp.IndexOf(">");
                        }

                        strHtmlStripped = strCodeTemp;
                        //strPreviewCodeTemp = strPreviewCode;
                        strPreviewCodeTemp = strPreviewCodeTemp.Replace(@"<Image>", "");
                        strPreviewCodeTemp = strPreviewCodeTemp.Replace(@"</Image>", "");

                        objBmp = oDraw.DrawShapeTolerance(strPreviewCodeTemp, strHtmlStripped, strFileTemp);
                    }
                    else
                    {
                        intCodeStartFlag = strPreviewCodeTemp.IndexOf("<T");
                        intCodeEndFlag = strPreviewCodeTemp.IndexOf("!");
                        if (intCodeStartFlag > -1)
                        {
                            //代码为上下标公差

                            strLeft = strPreviewCodeTemp.Substring(0, intCodeStartFlag);
                            strUp = strPreviewCodeTemp.Substring(intCodeStartFlag + 2, intCodeEndFlag - intCodeStartFlag - 2);
                            strDown = strPreviewCodeTemp.Substring(intCodeEndFlag + 1, strPreviewCodeTemp.Length - intCodeEndFlag - 2);
                            objBmp = oDraw.DrawTolerance(strLeft, strUp, strDown);
                        }
                        else
                        {
                            intCodeStartFlag = strPreviewCodeTemp.IndexOf("<H>");
                            intCodeEndFlag = strPreviewCodeTemp.IndexOf("</H>");
                            if (intCodeStartFlag > -1)
                            {
                                //代码为只有上公差
                                strLeft = strPreviewCodeTemp.Substring(0, intCodeStartFlag);
                                strUp = strPreviewCodeTemp.Substring(intCodeStartFlag + 3, intCodeEndFlag - intCodeStartFlag - 3);
                                strDown = "";
                                objBmp = oDraw.DrawTolerance(strLeft, strUp, strDown);
                            }
                            else
                            {
                                intCodeStartFlag = strPreviewCodeTemp.IndexOf("<L>");
                                intCodeEndFlag = strPreviewCodeTemp.IndexOf("</L>");
                                if (intCodeStartFlag > -1)
                                {
                                    //代码为只有下公差
                                    strLeft = strPreviewCodeTemp.Substring(0, intCodeStartFlag);
                                    strUp = "";
                                    strDown = strPreviewCodeTemp.Substring(intCodeStartFlag + 3, intCodeEndFlag - intCodeStartFlag - 3);
                                    objBmp = oDraw.DrawTolerance(strLeft, strUp, strDown);
                                }
                                else
                                {
                                    intCodeStartFlag = strPreviewCodeTemp.IndexOf("<√>");
                                    intCodeEndFlag = strPreviewCodeTemp.IndexOf("</√>");
                                    if (intCodeStartFlag > -1)
                                    {
                                        //代码为指定加工方法时
                                        strLeft = strPreviewCodeTemp.Substring(intCodeStartFlag + 3, intCodeEndFlag - intCodeStartFlag - 3);

                                        strRight = strPreviewCodeTemp.Substring(intCodeEndFlag + 4);
                                        objBmp = oDraw.DrawRoughness(strLeft, strRight);
                                    }
                                    else
                                    {
                                        intCodeStartFlag = strPreviewCodeTemp.IndexOf("<R>");
                                        intCodeEndFlag = strPreviewCodeTemp.IndexOf("</R>");
                                        if (intCodeStartFlag > -1)
                                        {
                                            //代码为去除材料时
                                            strLeft = strPreviewCodeTemp.Substring(intCodeStartFlag + 3, intCodeEndFlag - intCodeStartFlag - 3);

                                            strRight = "";
                                            objBmp = oDraw.DrawRoughness(strLeft, strRight);
                                        }
                                        else
                                        {
                                            intCodeStartFlag = strPreviewCodeTemp.IndexOf("<Q>");
                                            intCodeEndFlag = strPreviewCodeTemp.IndexOf("</Q>");
                                            if (intCodeStartFlag > -1)
                                            {
                                                //代码为不去除材料时
                                                strLeft = "";

                                                strRight = "";
                                                objBmp = oDraw.DrawRoughness(strLeft, strRight);
                                            }
                                            else
                                            {
                                                objBmp = null;
                                            }
                                        }
                                    }
                                }
                            }

                        }
                    }

                    //保存
                    if (objBmp != null)
                    {
                        //strFileDoc = strMapPath + @"\ImageTemp\";
                        //clsCon oCon = new clsCon();
                        String strImageTempPath;
                        //strImageTempPath = oCon.LoadConfigString("ImageTempPath");
                        strImageTempPath = webRootDir + ConfigurationManager.AppSettings["ImageTempPath"].ToString();

                        strFileDoc = strImageTempPath;
                        //if (Session["intMaxImageIndex"] == null)
                        //{
                        //    Session["intMaxImageIndex"] = 0;
                        //    intImageIndex = 1;
                        //}
                        //else
                        //{
                        //    intImageIndex = (int)Session["intMaxImageIndex"] + 1;
                        //}

                        strImageIndex = System.DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss_fff");
                        strFileName = "ImageTemp-" + strImageIndex + ".png";
                        //strFileName = "ImageTemp-" + intImageIndex + ".png";
                        strFilePath = strFileDoc + strFileName;
                        //System.Threading.Thread.Sleep(1);
                        //System.IO.FileInfo oFile = new System.IO.FileInfo(strFilePath);
                        //while (oFile.Exists == true)
                        //{
                        //    intImageIndex += 1;
                        //    strFileName = "ImageTemp-" + intImageIndex + ".png";
                        //    strFilePath = strFileDoc + strFileName;
                        //    oFile = new System.IO.FileInfo(strFilePath);
                        //}

                        System.IO.FileInfo oFile = new System.IO.FileInfo(strFilePath);
                        while (oFile.Exists == true)
                        {
                            strImageIndex = strImageIndex + "1";
                            strFileName = "ImageTemp-" + strImageIndex + ".png";
                            strFilePath = strFileDoc + strFileName;
                            oFile = new System.IO.FileInfo(strFilePath);
                        }

                        objBmp.Save(strFilePath);
                        // Session["intMaxImageIndex"] = intImageIndex;
                        if (Session["dtImage"] == null)
                        {
                            dtImage = new DataTable();
                            dtImage.Columns.Add("FileName");
                            dtImage.Columns.Add("HtmlCode");
                            Session["dtImage"] = dtImage;
                        }
                        else
                        {
                            dtImage = (DataTable)Session["dtImage"];
                        }

                        DataRow dr;
                        dr = dtImage.NewRow();
                        dr[0] = strFileName;
                        dr[1] = "<Image>" + strPreviewCodeTemp + "</Image>";
                        dtImage.Rows.Add(dr);
                        Session["dtImage"] = dtImage;

                        //strFileDoc = oCon.LoadConfigString("ImageTempPath");
                        //strFileDoc = ConfigurationManager.AppSettings["ImageTempPath"].ToString();
                        strFileDoc = ResolveUrl(webRootUrl + ConfigurationManager.AppSettings["ImageTempPath"].ToString());

                        // strHtml = "<img src='../../../ImageTemp/" + strFileName + "'>";
                        strHtml = @"<img src='" + strFileDoc + strFileName + "'>";
                        strPreviewCodeDis += strHtml;
                    }

                }
                if (intEndFlag + 8 < strPreviewCode.Length)
                {
                    strPreviewCode = strPreviewCode.Substring(intEndFlag + 8);
                    intStartFlag = strPreviewCode.IndexOf("<Image>");
                    intEndFlag = strPreviewCode.IndexOf("</Image>");
                }
                else
                {
                    intStartFlag = -1;
                }

            }
            intStartFlag = strPreviewCode.IndexOf("<Image>");
            if (strPreviewCode != "" && intStartFlag == -1)
            {
                strPreviewCodeDis += strPreviewCode;
            }
        }
        catch (Exception myError)
        {

        }

    }

    public String GetCode(string strNotes)
    {
        String strHtmlCode, strHtml, strHtmlTemp;
        strHtml = strNotes;
        try
        {
            DataTable dtImage = new DataTable();
            int i, intStartFlag, intEndFlag;
            dtImage = (DataTable)Session["dtImage"];

            // strHtml = txtQualityNotes.Text.Trim();
            strHtmlCode = strHtml;

            intStartFlag = strHtmlCode.IndexOf("<img");
            if (intStartFlag == -1)
            {
                intStartFlag = strHtmlCode.IndexOf("<IMG");
            }
            if (intStartFlag > -1)
            {
                intEndFlag = strHtmlCode.IndexOf(">", intStartFlag);
                ;
            }
            else
            {
                intEndFlag = -1;
            }

            if (dtImage != null)
            {
                if (dtImage.Rows.Count > 0)
                {
                    while (intStartFlag > -1)
                    {
                        strHtmlTemp = strHtmlCode.Substring(intStartFlag, intEndFlag - intStartFlag + 1);
                        for (i = 0; i <= dtImage.Rows.Count - 1; i++)
                        {
                            if (strHtmlTemp.IndexOf(@"/" + dtImage.Rows[i][0]) > -1)
                            {
                                strHtmlCode = strHtmlCode.Replace(strHtmlTemp, (String)dtImage.Rows[i][1]);
                                break;
                            }

                        }

                        intStartFlag = strHtmlCode.IndexOf("<img", intStartFlag + 1);
                        if (intStartFlag == -1)
                        {
                            intStartFlag = strHtmlCode.IndexOf("<IMG", intStartFlag + 1);
                        }
                        if (intStartFlag > -1)
                        {
                            intEndFlag = strHtmlCode.IndexOf(">", intStartFlag + 1);
                            ;
                        }
                        else
                        {
                            intEndFlag = -1;
                        }
                        //intEndFlag = strHtmlCode.IndexOf(">", intStartFlag + 1);
                    }

                }

            }

            return strHtmlCode;
        }
        catch (Exception myError)
        {
            DisplayMessage(myError.Message, false);
            return "";
        }
    }
    #endregion
}